import re
import globals
from msg import Message
from SendToNeighbours import send_message_to_neighbors
from WaitMessages import wait_till_neighbors_reply
from CheckDuplicates import check_duplicates
from ConvertFEMsgToString import convert_to_string
from EvictMessages import evict_messages_for_user
import configfile
import GetDataFromAuthServer

def get_messages_front_end (mp, user, broadcaster):

    if user == "" :
        return False

    try :
        globals.globalGetMessageRequestsLock.acquire()
        globalGetMessageRequests = globals.globalGetMessageRequests + 1
    finally :
        globals.globalGetMessageRequestsLock.release()

    returnMessageList = []

    data = GetDataFromAuthServer.get_user_metadata(user)
    metadata= data.split(',')
    firstName = metadata[0]
    lastName = metadata[1]
    userGroup = metadata[2]
    try :
        globals.globalCacheMessageListLock.acquire()
        for item in globals.globalCacheMessageList :
            print item
            if ',' in item.toUserName :
                receivers = item.toUserName.split(',')
                for i in receivers :
                    if (i == user) :
                        returnMessageList.append(item)
                    if (i == userGroup) :
                        if user not in item.groupList :
                            item.groupList.append(user)
                            returnMessageList.append(item)

            elif item.toUserName == user :
                returnMessageList.append(item)
            elif item.toUserName == userGroup :
                if user not in item.groupList :
                    item.groupList.append(user)
                    returnMessageList.append(item)

    except KeyError :
        print 'No such user'
    finally:
        globals.globalCacheMessageListLock.release()
    #print "returnMessageList is "
    #print returnMessageList

            #returnMessageString = returnMessageString + item.fromUserName + "," + item.messageText + ";"
    # print 'End printing message list'
    # broadcast a message to get messages from other nodes
    message = Message(mp.thisName, None, None, user + ',' + userGroup, 'get_message_for_user', broadcaster)
    failedSending = send_message_to_neighbors (mp, message)

    # print 'Failed sending to : ',
    # print failedSending

    # Destinations that the waitThread has to wait for
    #mapS = mp.ConfigurationMap[mp.thisName]

    # print 'Waiting destinations loop : '
    listDest = []
    for item in configfile.get_node_neighbors(mp.thisName) :
        if not item == mp.thisName :
            if not item == message.src:
                if item not in failedSending :
                    listDest.append(item)


    # print 'Waiting for neighbors : ',
    # print listDest

    returnMessageList = wait_till_neighbors_reply(listDest, user, returnMessageList)
    try :
        globals.globalGetMessageRequestsLock.acquire()
        globalGetMessageRequests = globalGetMessageRequests - 1
    finally :
        globals.globalGetMessageRequestsLock.release()

    if returnMessageList == False :
        if globalGetMessageRequests == 0 :
            try :
                globals.globalShutdownLock.acquire()
                globals.globalShutdown = False
            finally :
                globals.globalShutdownLock.release()
        return False

    # Start the wait thread
    #waitTh = WaitThread(Message.dest, user, returnMessageString)
    #waitTh.start()

    # Broadcaster checks for duplicates and converts the list into string

    #print 'Code reached in check duplicates returnMessageList is : '
    #print returnMessageList

    returnMessageList = check_duplicates(user, returnMessageList)
    #print 'After check duplicates List is : '
    #print returnMessageList
    #if broadcaster == mp.thisName :
    returnMessageString = convert_to_string(returnMessageList)
    print 'Return String is : ' + returnMessageString

    # Send a broadcast message to the other nodes to evict this user's messages their caches
    data = user
    evictMsg = Message(mp.thisName, None, None, data, 'evict_messages', mp.thisName)

    # evict the messages for this user
    evict_messages_for_user(mp, evictMsg, user)
    #rest of the nodes return the list of the messages

    return returnMessageString
